package com.hx.jvm.jvm.lagou.gc;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpsServer;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jxlgcmh
 * @date 2020-08-09 10:13
 * @description
 */
public class HeapOOM {
    public static final int _1MB = 1024 * 1024;
    static List<byte[]> list = new ArrayList<>();

    private static void oom(HttpExchange httpExchange) {
        String response = "oom begin";
        try {
            httpExchange.sendResponseHeaders(200, response.getBytes().length);
            OutputStream responseBody = httpExchange.getResponseBody();
            responseBody.write(response.getBytes());
            responseBody.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0; ; i++) {
            byte[] bytes = new byte[_1MB];
            list.add(bytes);
            System.out.println(i + "MB");
            // 调用
            memPrint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static void server() {
        try {
            HttpsServer server = HttpsServer.create(new InetSocketAddress(8888), 0);
            HttpContext context = server.createContext("/");
            context.setHandler(HeapOOM::oom);
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 内存日志打印
     */
    static void memPrint() {
        for (MemoryPoolMXBean memoryPoolMXBean : ManagementFactory.getMemoryPoolMXBeans()) {
            System.out.println(memoryPoolMXBean.getName() +
                    "committed:" + memoryPoolMXBean.getUsage().getCommitted() +
                    "used:" + memoryPoolMXBean.getUsage().getUsed());
        }
    }

    public static void main(String[] args) {
        server();
    }
}
